<template>
  <view>
    <view class="goods-list">
      <view v-for="(goods, index) in goodsList" v-bind:key="index" v-on:click="gotoDetail(goods)">
        <my-good v-bind:goods="goods"></my-good>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        //请求参数对象
        queryObj: {
          query: '',    //查询关键词
          cid: '',      //商品分类ID
          pagesize: 10,   //每页显示多少条数据
          pagenum: 1     //页码值          
        },
        goodsList: [],
        total: 0,
        isloading: false    //节流阀
      };
    },
    onLoad(options){
      this.queryObj.query = options.query || '';
      this.queryObj.cid = options.cid || '';
      console.log('queryObj: ',this.queryObj);
      this.getGoodsList();
    },
    methods: {
      async getGoodsList(callback){      
        this.isloading = true;
        const res = await uni.$http.get('/api/public/v1/goods/search', this.queryObj);        
        this.isloading = false;
        //数据请求完毕, 按需调用回调函数
        /*
          callback && callback(): 如果调用getGoodsList()方法的传递了callback,
          就执行callback所在的回调函数callback(), 没传递callback则不执行 callback()    
        */
        callback && callback();
        console.log('callback:', callback);
        
        if(res.data.meta.status != 200){
          return uni.$showMessage('数据请求失败...');
        }
        console.log('res', res);
        this.goodsList = [...this.goodsList,...res.data.message.goods];
        this.total = res.data.message.total;
      },
      gotoDetail(item){
        uni.navigateTo({
          url: "/subpkg/good_detail/good_detail?goods_id=" + item.goods_id
        })
      }
    },
    onReachBottom() {
      if(this.queryObj.pagesize * this.queryObj.pagenum >= this.total){
        return uni.$showMessage('数据加载完毕...');
      }
      //节流阀为true, 表示正在请求其它url
      console.log('isloading: ', this.isloading)
      if(this.isloading){
        return;
      }
      //页码值增加
      this.queryObj.pagenum = this.queryObj.pagenum + 1;
      console.log('此处停止两秒...');
      setTimeout(this.getGoodsList, 2000);      
    },
    onPullDownRefresh(){
      //重置相关数据
      this.queryObj.pagenum = 1;
      this.total = 0;
      this.isloading = false;
      this.goodsList = [];
      //重新发起请求
      this.getGoodsList(() => uni.stopPullDownRefresh());
    }    
  }
</script>

<style lang="scss">
  
</style>
